package com.giraffe.aiochat.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.giraffe.aiochat.model.Message;

import java.util.Objects;

public class MessageUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    public static String toJson(Message message) {
        Objects.requireNonNull(message, "Message cannot be null");
        try {
            return objectMapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Failed to convert message to JSON: " + e.getMessage(), e);
        }
    }

    public static Message fromJson(String json) {
        if (json == null || json.trim().isEmpty()) {
            throw new IllegalArgumentException("JSON string cannot be null or empty");
        }
        try {
            return objectMapper.readValue(json.trim(), Message.class);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Failed to parse JSON to message: " + e.getMessage(), e);
        }
    }
}